
package com.epam.video.test;

import com.epam.video.entities.Lection;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.List;

public class LectionsListActivity extends Activity {

  private ListView listView;

  private ArrayAdapter<String> listViewAdapter;

  private AsyncTask<Void, Void, Void> loadDataTask;

  private List<Lection> lections;

  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lections_layout);
    Config.instance().setContext(getApplicationContext());
    loadData();
    initListView();
  }

  private void loadData() {
    loadDataTask = new AsyncTask<Void, Void, Void>() {
      @Override
      protected Void doInBackground(final Void... params) {
        String lectionsJson = HttpUtils.executeRequest(AppConstants.LECTIONS_LIST_URL);
        lections = JsonParserUtils.parseLectionsList(lectionsJson);
        return null;
      }

      @Override
      protected void onPostExecute(final Void result) {
        super.onPostExecute(result);
        initData(lections);
      }

    }.execute(null);
  }

  private void initListView() {
    listViewAdapter = new ArrayAdapter<String>(this, R.layout.lection_item);
    listView = (ListView) findViewById(R.id.lections_listview);
    listView.setAdapter(listViewAdapter);
    listView.setItemsCanFocus(false);
    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    listView.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
        Lection lection = lections.get(position);
        if (lection != null) {
          Intent ivcIntent = new Intent(getApplicationContext(), VideoActivity.class);

          String ivcsListJson = HttpUtils.executeRequest(String.format(AppConstants.IVC_LIST_URL_FORMAT,
              lection.getId()));

          // just for now we put ivc id = 1. TBD
          ivcIntent.putExtra(VideoActivity.IVC_ID_EXTRA, "1");
          ivcIntent.putExtra(VideoActivity.IVC_LECTION_ID_EXTRA, lection.getId());
          ivcIntent.putExtra(VideoActivity.IVCS_JSON_EXTRA, ivcsListJson);
          startActivity(ivcIntent);
        }
      }
    });
  }

  private void initData(final List<Lection> lections) {
    for (Lection lection : lections) {
      listViewAdapter.add(lection.getName());
    }
  }
}
